package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    //商品系统-品牌管理查询
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        //获取检索条件key
        String key = (String)params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.eq("brand_id",key)
                    .or().like("name",key);
        }
        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void updateDetail(BrandEntity brand) {
        //保证冗余字段数据一致
        //修改品牌表数据时也一起修改其他表关联的数据
        this.updateById(brand);

        if (!StringUtils.isEmpty(brand.getName())){
            //修改品牌管理时会直接修改brand表的数据，但是存在关联表的brand数据不会更新，所有这里同步更新pms_category_brand_relation的brandId，name
            //这里只需要修改品牌名，修改菜单只会动品牌名，不会动分类名
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());
        }

        //TODO: 更新其他关联


    }

    @Override
    public List<BrandEntity> getBrandsByIds(List<Long> brandIds) {
        List<BrandEntity> brand = baseMapper.selectList(new QueryWrapper<BrandEntity>().in("brand_id", brandIds));
        return brand;
    }

}